package com.wuseguang.springcloud.service.impl;

import com.wuseguang.springcloud.dao.jdbc.PhoneBookJdbc;
import com.wuseguang.springcloud.service.PhoneBookService;
import com.wuseguang.springcloud.util.PaginationUtil;
import com.wuseguang.springcloud.util.PagingTool;
import com.wuseguang.springcloud.util.PinYinUtils;
import com.wuseguang.springcloud.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@Service
public class PhoneBookServicelmpl implements PhoneBookService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PhoneBookJdbc bookJdbc;

    /**
     * @描述 教师通讯录
     * @创建人 zm
     * @创建时间 2020/4/27
     */
    @Override
    public Result queryTeacherPhoneBook(String schoolId, String teacherId) {

        logger.info("查询教师信息 PhoneBookServicelmpl - > queryTeacherPhoneBook");

        String sql = "SELECT t.id,name,phone,head_portrait headPortrait,IF(b.id IS NULL,0,1 ) state   FROM `teacher` t LEFT JOIN phonebook b ON " +
                "(t.id=b.teacher_id_one AND b.teacher_id=?) WHERE t.school_id =?    ORDER BY CONVERT( name USING gbk ) ";

        Map<String, Object> mapList = new HashMap<>();
        logger.info("查询教师sql = {}", sql);
        //查询教师任课SQL
        String rkSql = "SELECT  GROUP_CONCAT(DISTINCT t.roleName SEPARATOR '|') string FROM ( select r.`name`  roleName from teacher_role  tr inner join `classes` c  on(tr.pid=c.id) LEFT join roles r on (tr.role_id=r.id) where tr.teacher_id =? and tr.type=3" +
                " UNION ALL " +
                "select r.`name`  roleName from teacher_role  tr inner join `grade` g  on(tr.pid=g.id) LEFT join roles r on (tr.role_id=r.id) where tr.teacher_id =? and tr.type=2" +
                " UNION ALL " +
                "select r.`name`  roleName from teacher_role  tr inner join `department` d  on(tr.pid=d.id) LEFT join roles r on (tr.role_id=r.id) where tr.teacher_id =? and tr.type=1  ) t";

        List<Map<String, Object>> list = bookJdbc.queryListMap(sql, teacherId, schoolId);
        //循环信息
        for (Map<String, Object> map : list) {
            String s = bookJdbc.queryString(rkSql, map.get("id"), map.get("id"), map.get("id"));
            map.put("roleName", s);
        }

        sql = "SELECT t.id,name,phone,head_portrait headPortrait,1 state FROM `teacher` t , phonebook b  WHERE t.school_id =?" +
                "AND t.id=b.teacher_id_one AND b.teacher_id=?  GROUP BY b.teacher_id_one";

        List<Map<String, Object>> careList = bookJdbc.queryListMap(sql, schoolId, teacherId);
        if (careList != null && careList.size() > 0) {
            for (Map<String, Object> map : careList) {
                String s = bookJdbc.queryString(rkSql, map.get("id"), map.get("id"), map.get("id"));
                map.put("roleName", s);
            }
        }
        mapList.put("careList", careList);
        List<TreeMap<String, Object>> lists = PinYinUtils.px(list, "name");
        mapList.put("list", lists);
        //返回数据
        return new Result(mapList);
    }

    /**
     * @描述 添加/取消被关注的人
     * @创建人 zm
     * @创建时间 2020/5/20
     */
    @Override
    public Result updateTeacherPhoneBook(String id, String teacherId, int state) {//关注的教师id 自己id  state 0 删除 1添加
        String sql = "insert into `phonebook` (`teacher_id`, `teacher_id_one`) values(?,?)";
        if (state == 1) {
            bookJdbc.updateByParameter(sql, teacherId, id);
        }
        if (state == 0) {
            sql = "delete from phonebook where teacher_id=? and teacher_id_one=?";
            bookJdbc.updateByParameter(sql, teacherId, id);
        }
        return new Result();
    }


    /**
     * @描述 查询家长通讯录
     * @创建人 zm
     * @创建时间 2020/4/27
     */
    @Override
    public Result queryParentPhoneBook(String schoolId, Integer classId, Integer indexNo, Integer rows) {

        logger.info("查询家长信息 PhoneBookServicelmpl - > queryParentPhoneBook");

        String sql = "SELECT  p.id,p.phone,CONCAT(t.student_name,'家长')  name,t.head_portrait  FROM  student t,parent_student s,parent p WHERE t.school_id=? AND t.class_id=? AND t.id=s.student_id AND s.parent_id=p.id ";

        List<Map<String, Object>> list = bookJdbc.queryListMap(sql, schoolId, classId);

        //创建分页工具
        PagingTool tool = new PagingTool();
        //放入页码
        tool.setIndexNo(indexNo);
        //放入每页显示数量
        tool.setRows(rows);
        //放入角色集合
        tool.setList(list);
        //返回数据
        return new Result(new PaginationUtil<>(list.size(), rows, tool.getList(), indexNo));
    }

    /**
     * @描述 教师通讯录 （家长端）
     * @创建人 zm
     * @创建时间 2020/5/20
     */
    @Override
    public Result queryTeacherPhoneBookBystudentId(Integer studentId) {//学生id
        String sql = "SELECT class_id,school_id FROM student s WHERE  s.id=?";
        Map<String, Object> map = bookJdbc.queryMap(sql, studentId);
        sql = "select id,name,phone,head_portrait headPortrait from `teacher` t where t.school_id = ? ";
        //判断如果classid不为空
        if (!StringUtils.isEmpty(map.get("class_id"))) {
            logger.info("班级不为空");
            sql += " and exists (select * from `teacher_role` tr WHERE tr.`teacher_id` =t.id and tr.`pid` =" + map.get("class_id") + " and tr.type=3 )";
        }
        //查询教师任课SQL
        String rkSql = "SELECT  GROUP_CONCAT(DISTINCT t.roleName SEPARATOR '|') string FROM ( select r.`name`  roleName from teacher_role  tr inner join `classes` c  on(tr.pid=c.id) LEFT join roles r on (tr.role_id=r.id) where tr.teacher_id =? and tr.type=3" +
                " UNION ALL " +
                "select r.`name`  roleName from teacher_role  tr inner join `grade` g  on(tr.pid=g.id) LEFT join roles r on (tr.role_id=r.id) where tr.teacher_id =? and tr.type=2" +
                " UNION ALL " +
                "select r.`name`  roleName from teacher_role  tr inner join `department` d  on(tr.pid=d.id) LEFT join roles r on (tr.role_id=r.id) where tr.teacher_id =? and tr.type=1  ) t";

        List<Map<String, Object>> list = bookJdbc.queryListMap(sql, map.get("school_id"));
        //循环信息
        for (Map<String, Object> map1 : list) {
            String s = bookJdbc.queryString(rkSql, map1.get("id"), map1.get("id"), map1.get("id"));
            map1.put("roleName", s);
        }
        return new Result(list);
    }
}
